#!/usr/bin/python
# -*-coding:utf-8-*-
# pip install ddddocr 图片识别
"""传感器组管理"""
import asyncio
import json
import os
import time
from datetime import datetime
from time import sleep
import requests
from dotenv import load_dotenv
import common
import db

mysqldb = db.DbManager()
load_dotenv(verbose=True)
# 今天
today_time = common.TodayTime()
# 将-替换为.
today_time_new = today_time.replace('-', '.')
# 账号
username = os.getenv('ADMIN')
passworld = os.getenv('PWD')

# 获取登录后cookie
async def get_cookie(page):
    cookies_list = await page.cookies()
    cookies = ''
    for cookie in cookies_list:
        str_cookie = '{0}={1};'
        str_cookie = str_cookie.format(cookie.get('name'), cookie.get('value'))
        cookies += str_cookie
    print(cookies)
    return cookies


def list_split(items, n):
    return [items[i:i + n] for i in range(0, len(items), n)]


def curl(gate_id):
    cookie_str = "JSESSIONID=C800668DDA71827B670F50DD8D216AFE;"
    cookies = {cookies.split('=')[0]: cookies.split('=')[-1] for cookies in cookie_str.split('; ')}
    data = {
        'start': 0,
        'limit': 100,
        'gateid': gate_id,
    }
    headers = {
        'referer': 'http://210.12.220.207:8003/adp/home/sensor/blank.jsp?modeindex=m101',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_16_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3542.0 Safari/537.36',
    }
    resp = requests.post(
        "http://210.12.220.207:8003/adp/gate/getPageSensorByGateid",
        headers=headers, cookies=cookies, data=data,timeout=20)
    json_text = json.loads(resp.text)
    print(json_text)
    list_html = json_text['data']
    print(len(list_html))
    time.sleep(1)
    for i in range(0, len(list_html)):
        # 查询是否存在 codeName
        list_html_list = list_html[i]
        codeName = ""
        if list_html_list['sn'] != None:
            new_data = {
                'sn': list_html_list['sn']
            }
            resp_code = requests.post(
                "http://210.12.220.207:8003/adp/sensor_state/getOne",
                headers=headers, cookies=cookies, data=new_data)
            print(resp_code)
            json_text_code = json.loads(resp_code.text)
            print(json_text_code)
            state = json_text_code['state']
            statemsg = json_text_code['statemsg']
            updatetime = json_text_code['updatetime']
        notes=list_html_list['notes']
        notes_arr = notes.split(',')
        try:
            lon=notes_arr[0]
            lat=notes_arr[1]
        except:
            lon=None
            lat=None
        now_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        info = {"g_id": list_html_list['gatewayid'], "guid": list_html_list['guid'],
                "sensorname": list_html_list['sensorname'],
                "state": state,
                "statemsg": statemsg,
                "servicetype": list_html_list['servicetype'],
                "sn": list_html_list['sn'],
                "sng": list_html_list['sng'],
                "create_old": list_html_list['updatetime'],
                "update_old": updatetime,
                "lon":lon,
                "lat":lat,
                }
        print(info)
        find_info = mysqldb.table_select_one(table='device_gate', field="id",
                                             where={"guid": list_html_list['guid']})
        # 存在数据则跳过
        if find_info:
            info['update_date'] = now_time
            # 更新
            mysqldb.table_update(table="device_gate", data=info,
                                 where="guid ='" + list_html_list['guid'] + "'")
        else:
            # 添加
            info['create_date'] = now_time
            print(info)
            mysqldb.table_insert(table='device_gate', data=info)

    sleep(1)


class Egas:
    def __init__(self):
        sql = 'SELECT gate_id FROM devices_info where gate_id is not null and cityId=6 order by id asc limit 200'
        mysqldb.execute(sql)
        self.org_ids = mysqldb.cur.fetchall()
        asyncio.get_event_loop().run_until_complete(self.main())

    async def main(self):
        list2 = list_split(self.org_ids, 2)
        print(list2)
        for i in range(len(list2)):
            # pageProduceRecordForReg/生产档案 pageDetectionForReg/企业自检 pageInventoryForReg/批次追溯 pageSoldRecordForReg/入市追溯 pagePatrolFromOrg/督查巡查 pageProductCheckFromOrg/产品抽检 pagePrintRecordForOrg/标签打印 pageHgzPrintRecordForOrg/合格证
            for key in range(len(list2[i])):
                print(list2[i][key]['gate_id'])
                curl(list2[i][key]['gate_id'])

Egas()
